package net.marvinlee.thestar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebView;

public class ViewPostDetailActivity extends Activity {

	WebView webview;
	protected ProgressDialog mBusy;
	final Handler mHandler = new Handler();
	String currentPost = "";
	String currentFeedTitle = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.post_view);

		Bundle dataBundle = (savedInstanceState == null) ? getIntent()
				.getExtras() : savedInstanceState;
		String selectedPost = dataBundle.getString("postUrl");
		currentPost = selectedPost;
		String selectedFeedTitle = dataBundle.getString("feedTitle");
		currentFeedTitle = selectedFeedTitle;
		Log.i("TheStar", "selectedFeed:" + selectedPost);
		if (selectedPost != null) {
			getPost(selectedPost);
			getIntent().putExtra("postUrl", selectedPost);

		} else {
			Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("No Post");
			builder.setMessage("No Post Selected or Error getting article");
			builder.setPositiveButton("OK", null);
			builder.show();
		}

	}

	private void getPost(String selectedPost)
	{

		mBusy = ProgressDialog.show(this,
		  "Downloading", "Getting article...", true, false);

        // Prepare a request object
        final String url = selectedPost;
		Thread t = new Thread()
		{
			public void run()
			{
				try
				{					
			        HttpClient httpclient = new DefaultHttpClient();
			        
					Log.i("TheStar", "url =" + url);
			        String printerFriendlyUrl = "http://thestar.com.my/services/printerfriendly.asp?";
			        String eCentralUrl = "http://star-ecentral.com/services/sprinterfriendly.asp?";
			        String finalUrl = "";
			        if (url.indexOf("star-ecentral.com")> 0)
			        {
			        	finalUrl = eCentralUrl + url.substring(url.indexOf("file="), url.indexOf("&amp;sec")) ;
			        }
			        else
		        	{
						Log.i("TheStar", "currentFeedTitle =" + currentFeedTitle);
			        	if (currentFeedTitle.equals("World Updates"))
	        			{
			        		String key = "NOOTR_RTRMDNC_0_";
			        		String url1 = url.substring(url.indexOf("file="), url.indexOf(key) +16);
			        		String url2 = url.substring(url.indexOf(key) +16, url.indexOf("&amp;sec"));
			        		finalUrl = printerFriendlyUrl + url1 + "India" + url2 + ".asp";
	        			}
			        	else{
			        		finalUrl = printerFriendlyUrl + url.substring(url.indexOf("file="), url.indexOf("&amp;sec")) + ".asp";
			        	}
		        	}
					Log.i("TheStar", "finalUrl =" + finalUrl); 
			        HttpGet httpget = new HttpGet(finalUrl); 
			 
			        // Execute the request
			        HttpResponse response;
			        String result = null; 
			        
			        
			        	httpget.setHeader("Referer", "http://thestar.com.my"); 
			            //Log.i("TheStar","Right before the HTTP Call");
			            response = httpclient.execute(httpget);
			            // Examine the response status
			            Log.i("TheStar",response.getStatusLine().toString());
			 
			            // Get hold of the response entity
			            HttpEntity entity = response.getEntity();
			            // If the response does not enclose an entity, there is no need
			            // to worry about connection release
			  
			            if (entity != null) {
			 
			                // A Simple JSON Response Read
			                InputStream instream = entity.getContent();
			                result= convertStreamToString(instream);
			                //Log.i("TheStar",result);
			 
			                 
			                // Closing the input stream will trigger connection release
			                instream.close();
			            } 
			            
			
			            final String mimeType = "text/html";
			            final String encoding = "utf-8";
			
			            //Log.i("TheStar","Going to set data to view");
			
			            webview = (WebView) findViewById(R.id.webview); 
			            webview.getSettings().setJavaScriptEnabled(true);
			            String baseUrl = "http://thestar.com.my/";
			            if (url.indexOf("star-ecentral.com")> 0)
				        {
			            	baseUrl = "http://star-ecentral.com/";
				        }
			            webview.loadDataWithBaseURL(baseUrl, result, "text/html", "UTF-8", baseUrl);
			            webview.setOnKeyListener(new OnKeyListener(){ 
							public boolean onKey(View v, int keyCode,
									KeyEvent event) { 
			
					            //Log.i("TheStar","onKeyEvent");
								if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
						            	Log.i("TheStar","Is going back...");
										/*if (webview.canGoBack())
										{
							            	Log.i("TheStar","Can go back...");
											webview.goBack();
				                            return true;
										}
										else
										{
							            	Log.i("TheStar","CanNOT go back..., finishing off");
											finishFromChild(getParent());
				                            return false;
										} */
										finishFromChild(getParent());
			                    }
								return true;
							}
			            	
			            }); 
		    			mBusy.dismiss();
			 
			        } catch (Exception e) 
					{
						Log.d("::Exception::", e.toString());
						final String errmsg = e.getMessage();
						final String errmsgFull = e.toString();

			    		mHandler.post(new Runnable() {
			    			public void run()
			    			{
			    				mBusy.dismiss();

			    				String errstr = ((errmsgFull != null) ? errmsgFull : errmsg);

			    				new AlertDialog.Builder(ViewPostDetailActivity.this)
			    					.setTitle("Error")
			    					.setMessage("An error was encountered while accessing the post: " + errstr)
			    					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			    						//whatever.
			    						public void onClick(DialogInterface dialog, int whichButton) {
			    							
			    						}
			    					}).create();
			    			}
			    		});
					}			    	
				}
			};

			t.start();		
		}
	
	private static String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState); 
	    //Log.d("TheStar", "Tab Screen is rotated"); 
		outState.putString("postUrl", currentPost);
		outState.putString("feedTitle", currentFeedTitle);
		String selectedFeed = outState.getString("feedUrl");
		String selectedFeedTitle = outState.getString("feedTitle");
	    Log.d("TheStar", "Tab View Post rotated:"+ selectedFeedTitle + " feed:" + selectedFeed); 
    }

}
